package com.jack.xiaoer.web.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jack.xiaoer.dto.FileDTO;
import com.jack.xiaoer.dto.FileUploadDTO;
import com.jack.xiaoer.util.AjaxResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.UUID;

/**
 * Created by Jackaroo Zhang on 2018/12/10.
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private final Logger logger = LoggerFactory.getLogger(FileController.class);

    private static final String ROOT_DIR = "D:\\JavaProject\\Xiaoer\\Xiaoer-wx\\src\\main\\webapp\\static";

    @PostMapping("/upload")
    public AjaxResponse upload(MultipartHttpServletRequest request) throws IOException {
        FileUploadDTO uploadResult = new FileUploadDTO();
        ArrayList<FileDTO> successFiles = Lists.newArrayList();
        ArrayList<FileDTO> failFiles = Lists.newArrayList();

        Iterator<String> filenameItr = request.getFileNames();
        while (filenameItr.hasNext()) {
            MultipartFile file = request.getFile(filenameItr.next());
            String oldFileName = file.getOriginalFilename(); // 原文件名称
            String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")); // 文件后缀名
            if (!file.isEmpty()) {
                String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;
                LocalDate localDate = LocalDate.now();
                String url = File.separator + localDate.getYear() + File.separator
                        + localDate.getMonthValue() + localDate.getDayOfMonth() + File.separator
                        + newFileName; // 文件相对路径
                String path = ROOT_DIR + url; // 文件在本机存储路径
                File destination = new File(path);
                try {
                    FileUtils.copyInputStreamToFile(file.getInputStream(), destination);
                } catch (Exception e) {
                    logger.error("文件上传失败，filename=" + oldFileName, e);
                    failFiles.add(new FileDTO(oldFileName));
                }
                successFiles.add(new FileDTO(oldFileName, newFileName, url));
            }
        }

        uploadResult.setFailFiles(failFiles);
        uploadResult.setSuccessFiles(successFiles);

        return AjaxResponse.success("文件上传成功", uploadResult);
    }

}
